#!/bin/sh
# Copyright (c) 2012, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.

# created on 2012-12-06

main() {
 CHANNELS="$HOME/hbo-scan.txt" # generate with w_scan, etc.

 if
  ! zap1 -x
 then
  echo "error: tzap" >&2
  exit 1
 fi

 zap1 2>&1 |
 grep --line-buffered "|" | # parse only data rows
 sed -un "1~2 p" | # skip every second to keep up
 while read X STATUS B X SIGNAL B X SNR B X BER B X UNC B LOCK; do
  printf "%s " `date +%H:%M:%S.%N`
  echo "st $STATUS sig $SIGNAL SNR $SNR BER $BER UNC $UNC $LOCK"
  DSIGNAL=`printf "%d" 0x$SIGNAL`
  DSIGNAL=`expr $DSIGNAL / 256`
  DBER=`printf "%d" 0x$BER`
  DBER=`expr \( $DBER + 99 \) / 100`
  if ! [ "$LOCK" = "FE_HAS_LOCK" ] ; then
   say "Lock."
  elif ! [ "$UNC" = "00000000" -o "$UNC" = "ffffffff" ] ; then
   say "Uncorrect."
  else
   if [ "$BER" = "00000000" ] ; then
    say "OK ${DSIGNAL}."
   elif ! [ "$SNR" = "ffff" ] ; then
    say "R $DBER"
   else
    say "$DBER"
   fi
  fi
 done
}

zap1() {
 real_zap "$@"
# mock_zap "$@"
}

mock_zap() {
 if [ "$1" != "-x" ]; then
  cat << EOF |
status 1f | signal 9999 | snr ffff | ber 000012b0 | unc 00000000
status 1f | signal 9999 | snr fffe | ber 000012b0 | unc 00000001 | FE_HAS_LOCK
status 1f | signal 9999 | snr fffe | ber 000012b0 | unc 00000000 | FE_HAS_LOCK
status 1f | signal 9999 | snr ffff | ber 000012b0 | unc 00000000 | FE_HAS_LOCK
status 1f | signal 9999 | snr ffff | ber 00000000 | unc 00000000 | FE_HAS_LOCK
status 1f | signal 9a9a | snr ffff | ber 00000000 | unc 00000000 | FE_HAS_LOCK
EOF
   while read LINE;do
    echo "$LINE"
    sleep 1
    echo "$LINE"
    sleep 1
   done
 fi
}

real_zap() {
 tzap -F -c $CHANNELS "RTL Klub" "$@"
# tzap -F -c $CHANNELS "Duna World" "$@"
}

say() {
 espeak -z -v english_rp+klatt2 "$@" 2>/dev/null
}

main "$@"

